package cipher

import (
	"crypto/cipher"
	"crypto/des"
	"fmt"
)




/**
加密明文,密钥长度随便输，会自动增减为8字节
 */
func DesCBCEncypt(src,key []byte) ([]byte,error) {

	expectKey,err:=checkKey(key,8)
	if err != nil {
		return nil,err
	}

	block, err := des.NewCipher(expectKey)
	if err != nil {
		return nil, err
	}
	src = PKCS5Padding(src, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, expectKey)
	crypted := make([]byte, len(src))
	blockMode.CryptBlocks(crypted, src)
	return crypted, nil
}



/**
解密明文
 */

func DesDecrypt(crypted, key []byte) ([]byte, error) {
	expectKey,err:=checkKey(key,8)
	if err != nil {
		return nil,err
	}
	block, err := des.NewCipher(expectKey)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, expectKey)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	return origData, nil
}


/**
加密明文,密钥长度随便输，会自动增减为24字节
 */
func Des3CBCEncypt(src,key []byte) ([]byte,error) {

	expectKey,err:=checkKey(key,24)
	if err != nil {
		return nil,err
	}
	block, err := des.NewTripleDESCipher(expectKey)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	fmt.Printf("block.BlockSize=%d",block.BlockSize())
	src = PKCS5Padding(src, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, expectKey[0:8])
	crypted := make([]byte, len(src))
	blockMode.CryptBlocks(crypted, src)
	return crypted, nil
}


/**
解密明文
 */
func Des3Decrypt(crypted, key []byte) ([]byte, error) {

	expectKey,err:=checkKey(key,24)
	if err != nil {
		return nil,err
	}

	block, err := des.NewTripleDESCipher(expectKey)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, expectKey[:8])
	origData := make([]byte, len(crypted))
	// origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	// origData = ZeroUnPadding(origData)
	return origData, nil
}